// 实现这个项目的构建任务

const gulp = require('gulp')

const swig = require('gulp-swig')
const scss = require('gulp-sass') //我这里得gulp-sass安装不上，实在没法装
const babel = require('gulp-babel')
const imagemin = require('gulp-imagemin')
const pluginUseref = require('gulp-useref')
const del = require('del')
const browserSync = require('browser-sync')
const htmlmin = require('gulp-htmlmin')
const uglify = require('gulp-uglify')
const cssclean = require('gulp-clean-css')
const gulpif = require('gulp-if')

const bs = browserSync.create()
/***
 *  gulp处理后的文件都放在dist文件夹下面。
 * ****/

const clean = ()=>{
  return del(['dist','temp'])
}

//首先是对于public内文件的处理(不做任何处理，直接放进dist文件夹内)
const extra = () => {
  return gulp.src('public/**', {base: 'dist'}) // **匹配所有的文件
    .pipe(gulp.dest('dist'))
}

//对于页面的处理，使用swig模板进行处理
const data = null
const page = () => {
  return gulp.src('src/**/*.html', {base: 'src'}) // src/**/*.html 适配src下面所有的html文件
    .pipe(swig({data}))
    .pipe(gulp.dest('temp'))
}

//对于scss的处理，需要用到gulp-scss插件进行处理
const style = () => {
  return gulp.src('src/assets/styles/*.scss', {base: 'src'})
    .pipe(scss())
    .pipe(gulp.dest('dist'))
}

//对于js的处理，主要是ES版本降级和代码压缩
const scripts = () => {
  return gulp.src('src/assets/scripts/*.js', {base: 'src'})
    .pipe(babel({presets: ['@babel/preset-env']}))
    .pipe(gulp.dest('dist'))
}

//对图片进行压缩
const images = () => {
  return gulp.src('src/assets/images/**', {base: 'src'})
    .pipe(imagemin())
    .pipe(gulp.dest('dist'))
}

//对于字体文件进行处理
const fonts = () => {
  return gulp.src('src/assets/fonts/**', {base: 'src'})
    .pipe(imagemin())
    .pipe(gulp.dest('dist'))
}

const useref = () => {
  return gulp.src('temp/**/*.html', {base: 'temp'})
    .pipe(pluginUseref({searchParams: ['temp', '.']}))
    .pipe(gulpif(/\.js$/),uglify())
    .pipe(gulpif(/\.css$/,cssclean()))
    .pipe(gulp.dest('dist'))
    .pipe(clean(['temp']))
}

const compile = gulp.parallel(page,style,scripts)
const build = gulp.parallel(clean,gulp.parallel(compile,images,fonts, extra))
const develop = gulp.series(compile,serve)

const serve = () => { //serve用来监听代码的变化从而将变化主动推送到浏览器
  gulp.watch('src/assets/styles/*.scss', style)
  gulp.watch('src/assets/scripts/*.js', scripts)
  gulp.watch('src/**/*.html', page)
  //以及等等
  bs.init({
    files: 'dist/**', //监听dist下面的所有文件，如果发生改变则热更新
    serve: {
      baseDir: ['temp', 'src', 'dist'],
      routes: { //如果存在这个配置项，找文件的时候会先来这里找,如果找不到再去找dist文件夹
        '/node_modules': 'node_modules'
      }
    }
  })
}


module.exports = {
  build,
  compile,
  serve,
  develop,
  clean
}

